import os
import shutil

import requests


from util.logger import get_looger

url = "https://game.gtimg.cn/images/lol/act/jkzlk/js//10/15.15.7-S16/hex.js"

logger = get_looger("金铲铲.log", __file__)

logger.info("爬虫启动......")
root = 'static/金铲铲/'
if os.path.exists(root):
    shutil.rmtree(root)
os.makedirs(root)
response = requests.get(url)
print(response.status_code)
print(response.text)
top_dic = response.json()
content = top_dic.get("data")
for id,item in content.items():
    # id = item.get("id")
    logger.info(f"开始爬取第{id}条")
    item_name = item.get("name")
    item_desc = item.get("desc")
    item_icon = item.get("icon")
    response = requests.get(item_icon)
    with open(f"{root}{item_name}.jpg", "wb") as f:
        f.write(response.content)
    text_path = f"{root}.txt"
    # 将字典转换为字符串保存（原代码直接写入字典会报错）
    text_content = f"ID: {id}\n名称: {item_name}\n描述: {item_desc}\n图片URL: {item_icon}"
    with open(text_path, "a", encoding="utf-8") as f1:  # 增加编码参数，避免中文乱码
        f1.write(text_content)
    logger.info(f"文本信息保存成功：{text_path}")

    #
    # print(f'ID:{id}')
    # print(f"名称：{item_name}")
    # print(f"描述：{item_desc}")
    # print(f'图片url：{item_icon}')

logger.info("爬虫结束...")